package com.example.interviewrecorder.view

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.core.content.edit
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.interviewrecorder.LyyApplicaiton
import com.example.interviewrecorder.LyyBaseActivity
import com.example.interviewrecorder.LyyDatabase
import com.example.interviewrecorder.R
import com.example.interviewrecorder.dao.LyyUserDao
import com.example.interviewrecorder.databinding.ActivityLoginBinding
import com.example.interviewrecorder.utils.showToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginActivity : LyyBaseActivity(), View.OnClickListener {
    private val lyyUserDao: LyyUserDao = LyyDatabase.getDatabase().getLyyUserDao()
    private lateinit var binding: ActivityLoginBinding
    private val sp by lazy {
        getSharedPreferences(PSWD_SP, MODE_PRIVATE)
    }
    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                LOGIN_SUCCESS -> {
                    showToast(getString(R.string.login_success_tip))
                    //勾选了记住密码
                    if(binding.checkedTextView.isChecked){
                        sp.edit {
                            putString(USER_NAME,binding.userNameEt.text.toString())
                            putString(PASSWORD,binding.passwordEt.text.toString())
                        }
                    }else{
                        sp.edit().clear().apply()
                    }
                }
                LOGIN_FAIL -> showToast(getString(R.string.login_fail_tip))
            }
        }
    }

    companion object {
        const val LOGIN_SUCCESS = 1
        const val LOGIN_FAIL = 2
        const val PSWD_SP = "user_data"
        const val USER_NAME="username"
        const val PASSWORD="password"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initEvents()
        initDatas()
    }

    private fun initDatas() {
        val username=sp.getString(USER_NAME,"")
        val pswd=sp.getString(PASSWORD,"")
        binding.userNameEt.setText(username)
        binding.passwordEt.setText(pswd)
        binding.checkedTextView.isChecked=username!!.isNotEmpty()
    }

    private fun initEvents() {
        binding.loginBtn.setOnClickListener(this)
        binding.registerTv.setOnClickListener(this)
        binding.findPsdTv.setOnClickListener(this)
        binding.checkedTextView.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.loginBtn -> login()
            R.id.registerTv -> startActivity(Intent(this, RegisterActivity::class.java))
            R.id.checkedTextView -> {
                binding.checkedTextView.toggle()
            }
            R.id.findPsdTv-> FindPasswordActivity.start()
        }
    }

    private fun login() {
        lifecycleScope.launch {
            launch(Dispatchers.IO) {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    val userName = binding.userNameEt.text.toString().trim()
                    val password = binding.passwordEt.text.toString().trim()
                    val list = lyyUserDao.queryAllUser()
                    var flag = false
                    for (user in list) {
                        if (userName == user.userName && password == user.password) {
                            flag = true
                            LyyApplicaiton.currUser = user
                            break
                        }
                    }
                    if (flag) {
                        val msg = Message.obtain()
                        msg.what = LOGIN_SUCCESS
                        handler.sendMessage(msg)
                        finish()
                        startActivity(Intent(this@LoginActivity, RecordListActivity::class.java))
                    } else {
                        val msg = Message.obtain()
                        msg.what = LOGIN_FAIL
                        handler.sendMessage(msg)
                    }
                }
            }
        }
    }

}